package com.example.teemor.es_demo.controller;

import com.example.teemor.es_demo.entity.User;
import com.example.teemor.es_demo.service.UserService;
import com.example.teemor.es_demo.service.UserBehaviorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/client/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final UserBehaviorService userBehaviorService;



    /**
     * 根据ID获取用户
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<User>> getUserById(@PathVariable Long id, HttpServletRequest request) {
        try {
            User user = userService.getUserById(id)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 记录用户行为
            userBehaviorService.recordPageView(id, request.getSession().getId(), 
                    "/api/users/" + id, request);
            
            return ResponseEntity.ok(ApiResponse.success(user, "获取用户成功"));
        } catch (Exception e) {
            log.error("Failed to get user by id: {}", id, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }







    /**
     * 搜索用户
     */
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<List<User>>> searchUsers(@RequestParam String keyword,
                                                              HttpServletRequest request) {
        try {
            List<User> users = userService.searchUsers(keyword);
            
            // 记录搜索行为
            userBehaviorService.recordSearch(null, request.getSession().getId(), 
                    keyword, "user", request);
            
            return ResponseEntity.ok(ApiResponse.success(users, "搜索用户成功"));
        } catch (Exception e) {
            log.error("Failed to search users with keyword: {}", keyword, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 检查用户名是否可用
     */
    @GetMapping("/check-username")
    public ResponseEntity<ApiResponse<Boolean>> checkUsername(@RequestParam String username) {
        try {
            boolean available = userService.isUsernameAvailable(username);
            return ResponseEntity.ok(ApiResponse.success(available, 
                    available ? "用户名可用" : "用户名已存在"));
        } catch (Exception e) {
            log.error("Failed to check username: {}", username, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 检查邮箱是否可用
     */
    @GetMapping("/check-email")
    public ResponseEntity<ApiResponse<Boolean>> checkEmail(@RequestParam String email) {
        try {
            boolean available = userService.isEmailAvailable(email);
            return ResponseEntity.ok(ApiResponse.success(available, 
                    available ? "邮箱可用" : "邮箱已存在"));
        } catch (Exception e) {
            log.error("Failed to check email: {}", email, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }



    /**
     * 获取用户行为统计
     */
    @GetMapping("/{id}/behavior-stats")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getUserBehaviorStats(
            @PathVariable Long id,
            @RequestParam(defaultValue = "7") int days) {
        try {
            Map<String, Object> stats = userBehaviorService.getUserRecentBehaviorStats(id, days);
            return ResponseEntity.ok(ApiResponse.success(stats, "获取用户行为统计成功"));
        } catch (Exception e) {
            log.error("Failed to get user behavior stats for user: {}", id, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取用户画像
     */
    @GetMapping("/{id}/profile")
    public ResponseEntity<ApiResponse<Object>> getUserProfile(@PathVariable Long id) {
        try {
            Object profile = userBehaviorService.getUserProfile(id);
            return ResponseEntity.ok(ApiResponse.success(profile, "获取用户画像成功"));
        } catch (Exception e) {
            log.error("Failed to get user profile for user: {}", id, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    // 通用API响应类
    @lombok.Data
    @lombok.AllArgsConstructor
    @lombok.NoArgsConstructor
    public static class ApiResponse<T> {
        private boolean success;
        private String message;
        private T data;
        private long timestamp;

        public static <T> ApiResponse<T> success(T data, String message) {
            return new ApiResponse<>(true, message, data, System.currentTimeMillis());
        }

        public static <T> ApiResponse<T> error(String message) {
            return new ApiResponse<>(false, message, null, System.currentTimeMillis());
        }
    }
}